<template>
    <div style="height:100%;">
       <mapBoxViewer 
        ref="refMap" 
        searchLeft="20px"
        @onInit="initMap"
        @onDrag="openPupop"
        @onDragEnd="openPupop"
        @onZoom="onChangeZoom"
        @onZoomEnd="onChangeZoom"
        :location="landInfo" />
       <PoiPopup v-if="showPop"  :popOption="popObjct" @toNext="btnOpen" @onClose="closePopup"  />

    </div>
</template>

<script setup>
import {ref,onMounted,watch } from "vue"
import {useUserStore} from '@/pinia/modules/user'
import mapBoxViewer from "@/components/gisMapBox/index.vue";
import PoiPopup from '@/components/gisMapBox/components/PoiPopup.vue';
import {getLandMiniList,getFarmCount} from '@/api/gis'
import {getPageList} from '@/utils/common'
const userStore = useUserStore()
const props = defineProps({
    detail:{
        type:Object,
        default:{}
    },
    landInfo:{
      type:Object,
      default:{}
    },
    params:{
      type:Object,
      default:{}
    },
    plantingPlanId:{
        type:String,
        default:''
    },
    selectLandList:{ 
         type:Array,
        default:[]
    },
    bottomList:{
        type:Array,
        default:[]
    }
})

const emit = defineEmits(['onOpen','complete'])
let mapView = null
let farmLandId=null
const dataList = ref([])
const refMap = ref(null)
const showPop = ref(false)
const popObjct = ref({})
const landInfoData = ref({})
watch(()=>props.landInfo,()=>{
  landInfoData.value = props.landInfo
  openPupop()
  showPop.value = true
  changeLandColors(props.landInfo?.farmLandId)
})

watch(()=>props.plantingPlanId,()=>{
    if(mapView){
        updateData()
    }
})
watch(()=>props.selectLandList,()=>{
    if(mapView && props.selectLandList.length>0){
        updateData()
    }
})

onMounted(()=>{
})

const openPupop =()=>{
    if(!showPop.value){return}
    let item = landInfoData.value 
    const point = refMap.value.getWindXY(landInfoData.value.longitude,landInfoData.value.latitude)
    const popOption = {
              title:item.farmLandNo,
              farmId:item.farmId,
              companyId:item.companyId,
              farmLandId:item.farmLandId,
              pic:item.pic,
              screenX: point.left,
              screenY: point.top+50,
              visible:true,
              mapX: item.longitude,
              mapY: item.latitude,
              footer:true,
              values: [
                  {
                      label: '地块名称',
                      value: item.farmLandName
                  },
                  {
                      label: '地块面积',
                      value:  Number(item.mapAreaSize||item.mapareasize||0).toFixed(2)+'亩'
                  },
                  {
                      label: '地块类型',
                      value: item.landTypeName||item.landtypename||'--'
                  },
                  {
                      label: '作物类型',
                      value: (item.cropName||'--')+','+(item.cropSeriesName||'--')
                  },
                  {
                      label: '地块位置',
                      value: item.locationAddress||item.locationaddress||'--'
                  },
              ],
              btnText:'查看所有农事记录',
            ...item
    }
    popObjct.value = popOption
}

const initMap =async (map)=>{
     mapView = map
     const res = await getFarmCount({companyId:userStore.userInfo.companyId,farmId:userStore.userInfo.farmId})
     if(res.success){
        let pages =getPageList(res.data?.farmLandCount||6000)
        let params ={farmId:userStore.userInfo.farmId, companyId:userStore.userInfo.companyId}
        pages.forEach(async (item)=>{
            window.setTimeout(async () => {
                let res =await getLandMiniList({...params,...item})
                if(res?.success){
                      dataList.value =dataList.value.concat(res.data.filter((item)=>item.geom!=null))
                       emit('complete',dataList.value)
                    if(item.page==1){
                        addLandList()
                    }else{
                        updateData()
                    }
                }
                }, item.page==1?0:(item.page*200));
        })
     }
}
const showLandColor=(currentHandleCount)=>{
  let count =0
    if(currentHandleCount>=1&&currentHandleCount<=5){
      count=1
    }else if(currentHandleCount>5&&currentHandleCount<=10){
      count=2
    }else if(currentHandleCount>10&&currentHandleCount<=15){
      count=3
    }else if(currentHandleCount>15&&currentHandleCount<=20){
      count=4
    }else if(currentHandleCount>=21){
      count=5
    }
    if(count==0){
        return '#25c289'
    }else{
        let colors=props.bottomList.find((m)=>m.count==count)?.color||'#25c289'
        return colors
    }

}

const updateData =()=>{
    let filterList =dataList.value.filter((item)=>item.plantingPlanId == props.plantingPlanId).map((item)=> {
        if(item?.geom && item.geom!='null' && item.geom !=null){
            let totalNum = props.selectLandList.find((m)=>m.farmLandId==item.farmLandId)?.totalNum||0
            return {
                type: 'Feature',
                id:item.farmLandId,
                properties: {
                    description: item.farmLandName+'\n'+totalNum+'次',
                    lineColor:showLandColor(totalNum),//'#25c289',
                    lineWidth:3,
                    opacity:totalNum>0?0.8:0,
                    ...item
                },
                geometry: {
                    type: 'Polygon',
                    coordinates: [JSON.parse(item.geom||'[]')]
                }
            }
        }
    })
    if(mapView){
       window.setTimeout(() => {
         mapView.getSource('polygons-source')?.setData({type: 'FeatureCollection', features:filterList})
      }, 200);
    }
    let list= dataList.value.filter((item)=>props.selectLandList.map((m)=>m.farmLandId).includes(item.farmLandId))
    let centerList =[]
    list.forEach((item)=>{
        centerList.push([Number(item.locationLongitude),Number(item.locationLatitude)])
    })
    refMap.value.locationCenter(centerList)
}


const addSourceData =()=>{
         mapView.addSource('polygons-source', {
            type: 'geojson',
            data: {
                type: 'FeatureCollection',
                features: dataList.value.map((item)=> {
                  if(item?.geom && item.geom!='null' && item.geom !=null){
                    return {
                        type: 'Feature',
                        id:item.farmLandId,
                        properties: {
                            description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                            lineColor:'#25c289',
                            lineWidth:1,
                            ...item
                        },
                        geometry: {
                            type: 'Polygon',
                            coordinates: [JSON.parse(item.geom||'[]')]
                        }
                    }
                  }
                })
            }
    })
}

const addLandList =()=>{
       addSourceData()
       //添加线条
       mapView.addLayer({
            'id': 'polygons-layer-line',
            'type': 'line',
            'source': 'polygons-source',
            'layout': {},
            'paint': {
                'line-color': ['get', 'lineColor'],
                'line-width': ['get', 'lineWidth']
            }
    })

    // 添加多边形图层-图层
    mapView.addLayer({
            'id': 'polygons-layer-fill',
            'type': 'fill',
            'source': 'polygons-source',
            'paint': { 
            'fill-opacity': ['get', 'opacity'],
            'fill-color':['get', 'lineColor'],
            //   'fill-color': [
            //     'case',
            //     ['boolean', ['feature-state', 'click'], false],
            //     '#59e3b1','rgba(255, 255, 255, 0)']
              },
            "interactive": true
        })

        // 添加多边形图层-文字
        mapView.addLayer({
            'id': 'polygons-layer-text',
            'type': 'symbol',
            'source': 'polygons-source',
            layout: {
                'text-field': ['get', 'description'],
                'text-size': 13,
                'text-anchor': 'center',
                'visibility': 'none',
                'text-offset': [0, 1.5],
                "text-translate": [0, 1],
                "text-translate-anchor": "map",
                'text-offset': [0, 1.5],
            },
            paint: {
                'text-color': '#ffffff',
                "text-halo-color": "#000000",
                 "text-halo-width": 1 
            },
            metadata: {
                'renderedOnServer': false
            }
        });
    

     mapView.on('click','polygons-layer-fill',(e)=> {
        let item = e.features[0]
        landInfoData.value = {
          ...item?.properties,
          longitude:item?.properties?.locationLongitude,
          latitude:item?.properties?.locationLatitude
        }
        showPop.value = true
        changeLandColors(item.id)
        openPupop()
      })

    //  mapView.on('mouseenter', 'polygons-layer-fill',(e)=> {
    //       mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');
    // })
    
    //  mapView.on('mouseleave', 'polygons-layer-fill', (e)=> {
    //       mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
    // })
}
const changeLandColors =(Id)=>{
    if(farmLandId){
            mapView.setFeatureState({source: 'polygons-source', id:farmLandId },{ click: false });
        }
    farmLandId=Id
    mapView.setFeatureState({source: 'polygons-source', id: Id },{ click: true });
}

const closePopup =()=>{
    if(farmLandId){
        mapView.setFeatureState({source: 'polygons-source', id:farmLandId },{ click: false });
        farmLandId=null
    }
    showPop.value = false
}

const onChangeZoom =(row)=>{

    if(row.currentZoom<15){
        showPop.value = false
        mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
    }else{
        mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');

    }
    openPupop()
}
const btnOpen =(val)=>{
   emit('onOpen',val)
}
</script>

<style lang="scss" scoped>

</style>